package com.mf.elephant.common.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@ControllerAdvice
public class GlobalDefaultExceptionHandler {

	// 日志
	public Logger logger = LoggerFactory.getLogger(getClass());

	// 默认出错页面
	public static final String DEFAULT_ERROR_VIEW = "common/error/error";

	@ExceptionHandler(value = Exception.class)
	public ModelAndView defaultErrorHandler(HttpServletRequest request, HttpServletResponse response, Exception e)
			throws Exception {

		// 记录日志
		logger.error("程序出错", e);

		// If the exception is annotated with @ResponseStatus rethrow it and let
		// the framework handle it - like the OrderNotFoundException example
		// at the start of this post.
		// AnnotationUtils is a Spring Framework utility class.
		if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) {
			throw e;
		}

		// 是否AJAX提交
		boolean isAjax = this.isAjaxSumbit(request);
		if (isAjax) {
			// 如果是ajax提交，则返回异常，供js处理
			// TODO 增加状态码的处理
			response.setContentType("text/xml;charset=UTF-8");
			PrintWriter writer = response.getWriter();
			writer.write(e.getMessage());
			writer.flush();
			return null;
		} else {
			// 如果不是ajax提交，则显示默认出错页面
			ModelAndView mav = new ModelAndView();
			mav.addObject("exception", e);
			mav.addObject("url", request.getRequestURL());
			mav.setViewName(DEFAULT_ERROR_VIEW);
			return mav;
		}
	}

	/**
	 * 判断是否ajax提交
	 *
	 * @param request
	 * @return
	 */
	private boolean isAjaxSumbit(HttpServletRequest request) {
		return (request.getHeader("accept").indexOf("application/json") > -1
				|| (request.getHeader("X-Requested-With") != null
				&& request.getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1));
	}
}
